package com.zl.zsk.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zl.zsk.constant.RetCode;
import com.zl.zsk.exception.InValidParamException;
import com.zl.zsk.pojo.MyTest;
import com.zl.zsk.pojo.SysMenu;
import com.zl.zsk.pojo.SysUser;
import com.zl.zsk.pojo.Test;
import com.zl.zsk.pojo.vo.PageInfo;
import com.zl.zsk.pojo.vo.Result;
import com.zl.zsk.pojo.vo.UserVo;
import com.zl.zsk.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.loader.plan.build.spi.LoadPlanTreePrinter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * @author lxb
 * @version 1.0.0
 * @desc:
 * @date 2020-03-13 15:56
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class IndexController {
    @Autowired
    private UserService userService;

    @Autowired
    private DefaultKaptcha captchaProducer;




    @GetMapping("/code/image")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        // store the text in the session
        //request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        //将验证码存到session
//        getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        out.flush();
        ImageIO.write(bi, "jpg", out);
//        int HANDSHAKE = 0,
//                BARCODE = 1,
//                PAY = 2,
//                FACE = 3,
//                SETTINGS = 4,
//                CANCEL = 5,
//                TINY_APP = 100,
//                COMERR_MSG = 2019;
//        //{"barcode":"280483238153715599","code":"","giveAmount":"0","giveIntegral":0,"offsetAmount":"0","openHlb":false,"orderAmount":"0.01","orderType":"01","payAmount":
//        //"0.01","payType":"21","rechargeAmount":"0","sn":"QCF420191020179428","userIntegral":0,"zfbMember":false}
//
//        String pData = "{ \"target\": \"QT\",\"content\": { \"bizNo\": \"123423\", \"totalAmount\": \"0.01\", \"from\": \"com.alipay.iot.iohub.demo\", \"method\": \"start\"}}";
//
//        //TestLoad.INSTANCE.Send2com(TINY_APP, pData);
//
//        LoadDLL.TestLoad.PDragonflyCallBack pCbDragonfly = new LoadDLL.TestLoad.PDragonflyCallBackImpl();
//        LoadDLL.TestLoad.INSTANCE.SetDragonflyCallback(pCbDragonfly);
////        LoadDLL.TestLoad.INSTANCE.AsyncSend2Com(TINY_APP, pData);
//        LoadDLL.TestLoad.INSTANCE.AsyncSend2Hid(TINY_APP,pData);
//
//        try {
//            Thread.sleep(100000);
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
////        return "success";
    }

    /**
     * 使用账号密码登录
     * @param
     * @return 返回一个jwt
     */
    @ApiOperation("通过账号密码来获取token")
    @GetMapping(value = "/login")
    public Result login(@ApiParam("登录账号") @RequestParam String loginName,@ApiParam("密码")@RequestParam String password,@ApiParam("验证码") @RequestParam int validCode){
        if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(password)){
            throw new InValidParamException(RetCode.BAD_REQUEST);
        }
        String s = userService.authLogin(loginName, password);
        return Result.success(s);
    }

    /**
     * 获取用户信息
     * @param token
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/get")
    public Result getUser(@RequestHeader String token){
        SysUser sysUser = userService.getUserFromToken(token);
        return Result.success(sysUser);
    }



    /**
     * 退出登录
     * @param token
     * @return
     */
    @ApiOperation("退出登陆")
    @GetMapping(value = "/quit")
    public Result logout(@RequestHeader String token){
        userService.logout(token);
        return Result.success();
    }

    /**
     * 获取用户菜单，使用获取用户信息也能得到
     * @return
     */
    @ApiOperation("获取用户菜单")
    @GetMapping("/menus")
    public Result getMenus(){
        List<SysMenu> userMenus = userService.getUserMenus();
        return Result.success(userMenus);
    }

    /**
     * 添加用户
     * @param sysUser
     * @return
     */
    @ApiOperation("添加用户")
    @PostMapping({"/add"})
    public Result addUser(@RequestBody SysUser sysUser){
        if(sysUser.getUserId()!=null){
            return Result.failure(RetCode.ILLEGAL_PARAM.msg,RetCode.ILLEGAL_PARAM.code);
        }
        userService.addUser(sysUser);
        return Result.success();
    }

    /**
     * 获取用户列表
     * @param userVo
     * @return
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public Result listUser(UserVo userVo){
        int page = userVo.getPage();
        if(page<1){
            userVo.setPage(1);
        }
        PageInfo<SysUser> list = userService.listUser(userVo);
        return Result.success(list);
    }

    /**
     * 编辑用户
     * @param sysUser
     * @return
     */
    @ApiOperation("编辑用户")
    @PutMapping("/edit")
    public Result editUser(@RequestBody SysUser sysUser){
        if(sysUser.getUserId() == null){
            return Result.failure(RetCode.DATA_EXCEPTION.msg,RetCode.DATA_EXCEPTION.code);
        }
        userService.editUser(sysUser);
        return Result.success();
    }




    /**
     * 修改密码，需要用户重新输入密码
     * @param
     * @return
     */
    @ApiOperation("修改密码")
    @PutMapping("/password")
    public Result editPassword(@ApiParam("旧密码") @RequestParam String oldPassword,
                               @ApiParam("新密码") @RequestParam String newPassword,
                               @ApiParam("确认密码")@RequestParam String confirmPassword){
        if(!newPassword.equals(confirmPassword)){
            return Result.failure("两次密码输入的不一致",RetCode.PASSWORD_NOT_SAME.code);
        }
        userService.editPassword(oldPassword,newPassword);
        return Result.success();
    }

    /**
     * 用户头像上传
     * @param file
     * @return 返回的路径其实是新生成的文件名
     */
    @ApiOperation("用户头像上传")
    @PostMapping("/avatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file){
        String path = userService.uploadAvatar(file);
        return Result.success(path);
    }

//    /**
//     * 回显图像给前端
//     * @param name
//     * @return
//     */
//    @ApiOperation("回显头像")
//    @GetMapping("/avatar")
//    public Result getAvatar(@RequestParam String name){
//        byte[] avatar = userService.getAvatar(name);
//        return Result.success(avatar);
//    }

    @ApiOperation("回显头像")
    @GetMapping("/avatar")
    public void getAvatar(@RequestParam String name, HttpServletResponse response) throws IOException {
        byte[] avatar = userService.getAvatar(name);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(avatar);
        outputStream.flush();
    }


}
